<style lang="scss">

.page-excel {
  .vue-code-mirror__con {
    max-height: 600px;
    overflow: auto;
  }
  --z-table-grid-editor-c-h: 516px;
}

.z-table-grid--render-v2 {
  .z-data-grid__select-def {
    background-color: rgba(59, 162, 244, 0.3);
    border: 1px solid rgba(59, 162, 244, 0.9);
  }

  .z-table-grid-select {
    z-index: 3;
  }

  .z-table-grid-con {
    > * {
      user-select: none;
    }
  }

  .z-table-grid-sti {
    position: sticky;
    left: 0;
    top: 0;
  }

  .z-table-grid-row-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    grid-template-rows: repeat(10, 50px);
    //z-index: -1;
    grid-template-columns: 1fr;

    .z-table-grid-editor__row {
      &:hover {
        background-color: var(--el-color-primary);
        color: #fff;
        .z-table-grid-editor__row-cell {
          border-right-color: transparent;
        }
      }
    }

    .z-table-grid-editor__row-cell {
      border-right: var(--z-table-border-right);
    }
  }

  .z-table-grid-bg {
    grid-template-rows: repeat(10, 50px);
    z-index: 1111;
    [rel-line] {
      border-bottom: none;
    }
  }

  .z-table-grid-bg2 {
    position: absolute;
    left: 0;
    top: 0;
    pointer-events: none;
    * {
      pointer-events: auto;
    }
    [data-def-cell] {
      //--data-def-cell-bg: #eee !important;
      &:not([isinshow]) {
        display: none;
      }
      opacity: 1 !important;
      border-right: var(--z-table-border-right);
      border-bottom: var(--z-table-border-bottom);
    }
  }

  .z-table-grid-editor-c {
    position: absolute;
    z-index: 10;
  }

  .z-table-grid-body {
    display: grid;
    position: relative;
    height: var(  --z-table-grid-editor-c-h);
    //overflow: auto;
    overflow-y: hidden;
    overflow-x: auto;
    //padding-bottom: 18px;
  }

  .z-table-grid-editor__row {
    display: grid;
    grid-template-columns: var(--z-grid-template-columns);
  }

  .z-table-grid-editor__cell {
    &.is-in-current-row {
      border-right-color: transparent;
      color: #fff;
    }
  }

  [data-is-in] {
    //background-color: #eee;
    border-right-color: transparent;
    border-bottom-color: transparent;
  }

  .z-table-grid-con {
    pointer-events: none;
  }

  [data-def-cell] {
    //--data-def-cell-bg: #eee;
    opacity: 0;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: calc(100%);
      height: calc(100%);
      background-color: var(--data-def-cell-bg, #fff);
    }
    > [data-def-cell-content] {
      position: absolute;
      left: 0;
      top: 0;
      width: calc(100%);
      height: calc(100%);
      z-index: 22;
    }
  }
}

scrollable-component {
  overflow: auto;
}

.scroll-default {
  --scrollbar-track-fill-color: #eee;
  --scrollbar-track-fill-color-hover: #eee;
}

.scroll-title {
  position: sticky;
  top: 0;
}

.scroll-carousel {
  --scrollbar-padding: 0;
  --scrollbar-width: 12px;
  --content-padding: 0 0 25px 0;
  background: linear-gradient(to top, #f9f8f7 12px, transparent 12px);
  overflow-y: hidden;
  overflow-x: auto;
}

.demo1-cell-title {
  width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

</style>

<template>
 <div>
   <el-slider @wheel.native="handleScrollWheel" v-model="scrollVar"  show-input :show-tooltip="false" :max="scrollMax" @input="onSliderChange" ></el-slider>

<!--   <div style="overflow: auto; height: 300px;">-->
<!--     <div style="height: 10000px">11</div>-->
<!--   </div>-->


   <zw-row class="page-excel">
     <zw-col span="3">
       <div class="app-scrollbar" style="height: 80vh; overflow: auto">
         {{formatNumber(defRowLen)}}条
         <div>
           <a href="https://stackoverflow.com/questions/16637530/whats-the-maximum-pixel-value-of-css-width-and-height-properties">
             DIV最大显示高度
           </a>

           <pre>
Firefox: 33554400px
Chrome:  33554428px
Opera:   33554428px
IE 9:    21474836.47px
          </pre>
         </div>
       </div>
     </zw-col>
     <zw-col span="21">
       <z-space  vertical>
         <excel-form>
           <z-data-grid-form ref="form">
             <div
                 v-if="dataGrid.state.loaded">
               <z-data-grid-v2
                   ref="grid"
                   :vistrual-row="scrollBuffer"
                   :def="dataGrid.state.result"
                   :render-cell="renderCell"
                   @cell-click="onCellClick"
                   @grid-wheel="handleScrollWheel"
               ></z-data-grid-v2>
             </div>
           </z-data-grid-form>
         </excel-form>
         <div>
           <el-button @click="submit">submit</el-button>
         </div>
       </z-space>
     </zw-col>
   </zw-row>
 </div>
</template>

<script>
import VueCodeMirror from "@example/components/VueCodeMirror";
import {SortByIndex, useDataGrid} from "../../../babel-static/hooks";
import './excel/directive'

import ExcelText from "@example/views/grid/components/excelText";
import ExcelForm from "@example/views/grid/components/ExcelForm";


export function formatNumber(num) {
  num = Number(num);
  if (num == 0) {
    return num + '';
  } else
  if (num > 1 && num < 10000) {
    return num + '';
  } else {
    let x = (num / 10000).toFixed(2)

    let a = x.split('.');
    if (a[1] === '00') {
      x = a[0]
    }

     return x   + '万';
  }
}

function getRange(arr = []) {
  let nth = ZY.lodash.nth;
  // let b = arr.map(function (v){
  //   return v.dataset
  // });
  let b = arr
  b = SortByIndex.sortArr(b, 'key');
  if (b.length < 1) {
    return null
  }
  // console.log(b)
  return [b[0]?.key, nth(b, -1)?.key]
}

let globalArr;

let scrollMixin = {
  data() {
    let scrollBuffer = 10;
    return {
      scrollBuffer,
      scrollVar: 0,
      scrollMax: this.defRowLen - scrollBuffer
    }
  },
  methods: {
    handleScrollWheel(e) {
      // console.log('handleScrollWheel', e)
      let self = this;

      window.requestAnimationFrame(() => {
        // console.log(self.scrollVar)
        if (e.deltaY < 0)
        {
          if (self.scrollVar < 1) {
            return;
          }
          self.scrollVar = self.scrollVar - 1;
          // console.log('scrolling up');
        }
        else if (e.deltaY > 0)
        {
          self.scrollVar = self.scrollVar + 1;
          // console.log('scrolling down');
        }
      })
    },
    onSliderChange(v) {
      // console.log('scrollToRowLine', v, this.$refs.grid)

      if (this.$refs.grid) {

        this.$refs.grid.scrollToRowLine(v)
      }
    }
  }
}

export default {
  components: {ExcelForm, ExcelText, VueCodeMirror},
  mixins: [
    scrollMixin
  ],
  data() {
    let self = this;
    return {
      id: ZY.rid(),
      batchOption: {
        selectIdxs: [],
        getScrollY() {
          return 0
        },
        selector: '[data-grid-cell]',
        onMouseMove(elArr, doms, area) {
          // let el =  self.$refs.grid.$el
          // console.log('onMouseMove', 'huijia')
          // let elPos = el.getBoundingClientRect();
          let _elArr = globalArr(elArr)
          let range = getRange(_elArr);
          // console.log('range', elArr)
          // if (range[0] === range[1]) {
          //   range[1] =
          // }
          // let domArr = doms.filter(v => {
          //   return range.includes(v.dataset.key)
          // });
          // let posArr = domArr.map(v => {
          //   return  v.getBoundingClientRect()
          // })
          // // console.log(domArr, posArr)
          // let startX = Math.min(posArr[0].left, posArr[1].left)
          // let startY = Math.min(posArr[0].top, posArr[1].top)
          //
          // let endX = Math.max(posArr[0].left + posArr[0].width, posArr[1].left + posArr[1].width)
          // let endY = Math.max(posArr[0].top + posArr[0].height, posArr[1].top + posArr[1].height)
          //
          // const left = startX - elPos.x;
          // const top = startY - 80;
          // const width = Math.abs(endX - startX) - 2
          // const height = Math.abs(endY - startY) - 2
          //
          // self.$nextTick(() => {
          //   area.style.left = `${left}px`
          //   area.style.top = `${top}px`
          //   area.style.width = `${width}px`
          //   area.style.height = `${height}px`
          //
          // })
          // console.log(range, posArr, area);
          if (range && range.length > 1) {
            // self.$refs.grid.setSelectDefs(range[0], range[1])
          }
        }
      }
    }
  },
  computed: {
    layoutSelector() {
      let nth = ZY.lodash.nth;
      let arr  = ZY.lodash.get(this, 'batchOption.selectIdxs', []);
      let b = arr.map(function (v){
          return v.dataset
      });
      let _elArr = globalArr(b)
      b = SortByIndex.sortArr(_elArr, 'key');
      if (b.length < 1) {
        return null
      }
      // console.log(b)
      return [b[0]?.key, nth(b, -1)?.key]
    }
  },
  watch: {
    layoutSelector(newVal) {
      // console.log('layoutSelector', newVal, this.$refs.grid)
      if (newVal && newVal.length > 1) {
        this.$refs.grid.setSelectDefs(newVal[0], newVal[1])
      }
    }
  },
  methods: {
    formatNumber,
    renderCell({ rowLineNum, columnNum, index}) {
      // console.log(rowLineNum, columnNum)
      // let row = __test_data__[rowLineNum - 1];
      // if (row) {
      //   let cell = row['p' + (columnNum - 1)];
      //   // return (<zw-div aspect="10:1"> <zw-truncate text={cell + ''}></zw-truncate> <div >{index + 1}</div> <div>{rowLineNum}</div></zw-div>)
      //   return (<ExcelText row={rowLineNum - 1} column={columnNum - 1}  text={cell + ''}></ExcelText>)
      // }
      // return (<div><div>{index + 1}</div> <div>{rowLineNum}</div></div>)
      return (<ExcelText row={rowLineNum - 1} column={columnNum - 1}  text={ ''}></ExcelText>)
    },
    onCellClick(e) {
      if (!e.shiftKey) {
        // console.log('onCellClick', e.target);
        let key = e.target?.dataset?.key;
        let lastKey = e.target?.dataset?.lastKey;
        // console.log('key',  e.target.getBoundingClientRect())
        if (key && lastKey) {
          // this.$refs.grid.setSelectDefs(key, lastKey)
        }
      }
    },
    async submit() {
      let {
        ext, isValid, errors, data, obj
      } = await  this.dataGrid.submit(this.$refs.form)

      console.log(ext, isValid, errors, data, obj)
    },
    setData() {
      this.$refs.form.setData({
        name:'测试'  + ZY.rid(3)
      })
    }
  },
  setup() {
    // let defRowLen = 3000000
    let defRowLen = 30000
    let defColumnLen = 15
    globalThis.__test_data__ = [];

    let a = new URL('http://localhost' + location.hash.slice(1))
    let formName = a.searchParams.get('name') ?? '测试'
    let dataGrid = useDataGrid({
      url: '/api/demo1/form',
      opt:{
        params: {
          formName
        },
        headers: {
          ['X-Access-Token']: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTI3MzYwMTIsInVzZXJuYW1lIjoiYWRtaW4ifQ.BYG8oysR9xCge3zEyv7vIfvJ9ONS9NdsJGboSPlTpEY'
        }
      },
      onReady(res) {
        res.result.selectDefs = [
          // {
          //       "id": ZY.rid(6),
          //   "range": "A1:A3",
          //   // letterSingle: "A2",
          //   style: {
          //         backgroundColor: "#3f3f3f"
          //   },
          //   // isSingle: true
          //   // cArr: [0,0],
          //   // rArr: [3,3]
          // }
        ];
        res.result.origin.config.rowlen = {
          // 6: 100
        }

        let key = rowAndColumnToKey(defColumnLen, defRowLen)
        res.result.defs = res.result.defs.concat([
          // {
          //   id: ZY.rid(6),
          //   range: "B3:D4",
          // },
          // {
          //   id: ZY.rid(6),
          //   range: "B30:D32",
          // },
          {
            id: ZY.rid(6),
            range: `${key}:${key}`
          }
        ])
      }
    })

    globalArr = function (arr = []) {
      let a = [];
      let map = dataGrid.getResult().mergeMap ?? {}
      arr.forEach(item => {
        if (map.hasOwnProperty(item.key)) {
          a.push({
            key: map[item.key].end
          })
        }
      })
      return  arr.concat(a)
    }



    return {
      defRowLen,
      defColumnLen,
      dataGrid,
    }
  },
  mounted() {
    let self = this;
    let index = 0;
    let totalRecycle = 10;
    let initLen = 10000;

    function makeArrayOf(value, length) {
      var arr = [], i = length;
      while (i--) {
        arr[i] = value(i);
      }
      return arr;
    }


    function loopAppend() {
      let s = makeArrayOf(function (i) {
        let id = ZY.rid(6);
        // let sid = ZY.rid(6);

        let obj = {
          id: id,
          // name: 'name_' + id
        }

        // let v =  'p__' + id

        for (let i = 0; i < 30; i++) {
          obj['p' + i] = 'p__' + id
          // obj['p' + i] = v
        }

        // var i = columnLenCalc;
        // while (i--) {
        //   obj['p' + i] = v
        // }
        // obj['p0'] = v
        // for (let i = 30; i > -1; i--) {
        //   obj['p' + i] = 'p__' + id
        // }
        return obj
      }, initLen)

      globalThis.__test_data__ = globalThis.__test_data__.concat(
          s
      );

      if (index < totalRecycle) {
        index = index + 1;
        setTimeout(() => {
          loopAppend()
        }, 300)
      }
    }

    setTimeout(() => {
      console.time('111')



      loopAppend();

      // console.log( globalThis.__test_data__)
      console.timeEnd('111')
      self.$refs.grid.forceRender();
    }, 300)
  }
}
</script>
